<template>
  <div>
    <div v-if="peerInfo.peerId">
      <h3 v-if="peerInfo.peerId">通信🆔：{{ peerInfo.peerId }}</h3>
      <h3 v-if="dataConnection">已🐟链接</h3>
    </div>
    <hr>

    <div>
      <input v-model="shareUserId" placeholder="输入分享人ID"/>
      <button @click="connect">连接</button>
    </div>

    <div>
      <div v-for="(item,index) in msgList">
        {{item}}
      </div>
    </div>
    <div>
      <input v-model="msg" placeholder="文本消息"/>
      <button @click="sendMsg">发送消息</button>

    </div>
  </div>
</template>

<script setup>
// 导入 vue-router
import {useRoute} from 'vue-router'

const route = useRoute()
import {onMounted, reactive, ref} from "vue";
import Peer from "peerjs";

const shareUserId = ref("")
const msg = ref("")
const dataConnection = ref(null)

const msgList=ref([])

const peerInfo = reactive({
  peerId: "",
})


const peer = new Peer({
  host: '127.0.0.1',
  port: 8888,
});

peer.on("open", function (id) {
  console.log(id)
  peerInfo.peerId = id
})

//被连接的回调
peer.on("connection", (conn) => {
  conn.on("data", (data) => {
    console.log(data);
    msgList.value.push("好友："+data)
  });
  conn.on("open", () => {
    dataConnection.value = conn
  });
});


const sendMsg = () => {
  dataConnection.value.send(msg.value)
  msgList.value.push("我："+msg.value)
  msg.value = "";

}

const connect = () => {
  dataConnection.value = peer.connect(shareUserId.value);
  //连接对方的回调
  dataConnection.value.on("open", () => {
    console.log("连接成功");
  })
  dataConnection.value.on("data", (data) => {
    console.log(data);
    msgList.value.push("好友："+data)
  });
}


</script>

<style scoped>
</style>
